package com.watson.activity;

import static com.watson.fragment.HomeFragment.U_DEPOT_ID;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.watson.BaseActivity;
import com.watson.MyApp;
import com.watson.R;
import com.watson.adapter.QuestAdapter;
import com.watson.adapter.SourceZAdapter;
import com.watson.bean.ChooseBean;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class QuestActivity extends BaseActivity {
    private XRecyclerView mRecyclerview;
    private QuestAdapter questAdapter;
    private LinearLayout lyNoLayout;
    private ArrayList<Map> dataList = new ArrayList<>();
    private TextView tvTitle, tvRight, tvUserName;
    private int page = 1;
    private int isStatus = 1;
    private EditText etStr;
    private ImageView imgSys;
    private int standingss = 0;
    private boolean isLoadMore = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quest);

        statusbar4();
        findViewById(R.id.imgBack).setOnClickListener(v -> finish());
        mRecyclerview = findViewById(R.id.mXRecyclerView);
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText(getIntent().getStringExtra("name"));
        tvRight = findViewById(R.id.tvRight);
        tvUserName = findViewById(R.id.tvUserName);
        etStr = findViewById(R.id.etStr);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("筛选");
        lyNoLayout = findViewById(R.id.lyNoLayout);
        lyNoLayout.setVisibility(View.GONE);
        imgSys = findViewById(R.id.imgSys);
        int standing = StringUtils.isEmpty(SPUtils.get(mContext, "standing", "") + "") ? -1 : Integer.valueOf(SPUtils.get(mContext, "standing", "") + "");
        standingss = standing;
        if (standing == 1) {
            imgSys.setVisibility(View.VISIBLE);
            imgSys.setImageDrawable(getResources().getDrawable(R.mipmap.icon_xuan2));
            imgSys.setOnClickListener(v -> {
                if (standingss == 1) {
                    standingss = 0;
                    imgSys.setImageDrawable(getResources().getDrawable(R.mipmap.icon_xuan1));
                } else {
                    standingss = 1;
                    imgSys.setImageDrawable(getResources().getDrawable(R.mipmap.icon_xuan2));
                }

                page = 1;
                get_WMS_OutboundTaskList();
            });
        } else {
            imgSys.setVisibility(View.GONE);
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false);
        mRecyclerview.setLayoutManager(layoutManager);
        mRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
        questAdapter = new QuestAdapter(mContext, dataList);
        mRecyclerview.setAdapter(questAdapter);
        questAdapter.setItemClickListener((position, mList) -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            Intent intent = new Intent(mContext, Details2Activity.class);
            intent.putExtra("no", mList.get(position).get("no") + "");
            intent.putExtra("zt", mList.get(position).get("zt") + "");
            intent.putExtra("type", 2);
            startActivityForResult(intent, 1001);
        });

        stateList = new ArrayList<>();

        for (int i = 0; i < state.length; i++) {
            ChooseBean chooseBean = new ChooseBean();
            chooseBean.setId(i);
            chooseBean.setName(state[i]);
            stateList.add(chooseBean);
        }
        stateList.get(0).setType(-1);

        mRecyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore = true;
                page = 1;
                get_WMS_OutboundTaskList();
            }

            @Override
            public void onLoadMore() {
                if (isLoadMore) {
                    page++;
                    get_WMS_OutboundTaskList();
                } else {
                    mRecyclerview.refreshComplete();
                    mRecyclerview.setPullRefreshEnabled(true);
                }
            }
        });

        mRecyclerview.refresh();
        mRecyclerview.refreshComplete();
        mRecyclerview.setPullRefreshEnabled(true);

        tvUserName.setOnClickListener(v -> {
            dismiss();
            initPopupWindow(tvUserName, stateList);
        });
        tvRight.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            dismiss();
            initPopupWindow(tvRight, stateList);
        });

        lyNoLayout.setOnClickListener(v -> {
            page = 1;
            get_WMS_OutboundTaskList();
        });
    }

    private String noStr = "";
    private int isType = 0;

    private void get_WMS_OutboundTaskList() {
        Map dataMap = new HashMap();
        dataMap.put("u_id", SPUtils.get(mContext, "U_Id", "") + "");//用户名
        dataMap.put("r_id", standingss);//登录用户角色名
        dataMap.put("wh", U_DEPOT_ID + "");//作业仓库
        dataMap.put("status", isStatus);//任务状态 1进行中 2已完成 3暂存 0作废 4全部
        dataMap.put("pageIndex", page);//页码
        dataMap.put("pageSize", 10);//页容量
        dataMap.put("where", noStr);//条件内容类型
        dataMap.put("type", isType);//type 1单号，2客户，3客服 无条件默认0
//        dataMap.put("standing", standingss);
        String str = new Gson().toJson(dataMap);
        LogUtils.e("TAG", "str:" + str);

        HttpClient.getInstance().postData(CommonHttpConsts.get_WMS_OutboundTaskList, "get_WMS_OutboundTaskList")//
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(str)
//                .params("u_id", SPUtils.get(mContext, "U_Id", 0) + "")//用户名
//                .params("r_id", SPUtils.get(mContext, "standing", 0) + "")//登录用户角色名
//                .params("wh", U_DEPOT_ID + "")//作业仓库
//                .params("status", isStatus)//任务状态 1进行中 2已完成 3暂存 0作废 4全部
//                .params("pageIndex", page)//页码
//                .params("pageSize", 10)//页容量
                .execute(new HttpCallbackData() {

                    @Override
                    public void onError() {
                        super.onError();
                        ToastUtil.show("网络异常请稍后再试！");
                        if (page == 1) {
                            lyNoLayout.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            if (page == 1) {
                                dataList = (ArrayList<Map>) JSON.parseArray(info + "", Map.class);
                            } else {
                                ArrayList<Map> dataList1 = (ArrayList<Map>) JSON.parseArray(info + "", Map.class);
                                if (dataList1.size() > 0) {
                                    dataList.addAll(dataList1);
                                } else {
                                    isLoadMore = false;
                                }
                            }
                            if (dataList.size() == 0) {
                                isLoadMore = false;
                            }
                            questAdapter.setData(dataList);
                            if (dataList.size() == 0) {
                                lyNoLayout.setVisibility(View.VISIBLE);
                            } else {
                                lyNoLayout.setVisibility(View.GONE);
                            }
                        } else {
                            if (page == 1) {
                                lyNoLayout.setVisibility(View.VISIBLE);
                            } else {
                                lyNoLayout.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        mRecyclerview.refreshComplete();
                        mRecyclerview.setPullRefreshEnabled(true);
                    }
                });
    }

    private PopupWindow popupWindow;
    private ArrayList<ChooseBean> stateList;
    private String[] state = {"未完成", "已完成", "全部"};

    private void initPopupWindow(View data, ArrayList<ChooseBean> popList) {
        View view = View.inflate(mContext, R.layout.layout_popup_hint, null);
        RecyclerView recyclerPop = view.findViewById(R.id.recyclerPop);
        recyclerPop.setLayoutManager(new LinearLayoutManager(mContext));
        SourceZAdapter sourceAdapter = new SourceZAdapter(mContext, popList);
        recyclerPop.setAdapter(sourceAdapter);
        popupWindow = new PopupWindow(view, 150, ViewGroup.LayoutParams.WRAP_CONTENT);

        view.setBackgroundColor(mContext.getResources().getColor(R.color.tv6060));
        // 设置PopupWindow的遮罩层颜色
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 点击框外可以使得popupwindow消失
        popupWindow.setFocusable(true);
        //设置可以触摸弹出框以外的区域
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        // 获取右侧控件的位置
        int[] location = new int[2];
        data.getLocationOnScreen(location);
        // 计算PopupWindow的显示位置
        int xPos = location[0] + data.getWidth(); // 水平位置从控件右侧开始
        int yPos = location[1] + data.getHeight() + 5; // 垂直位置从控件下方开始

        popupWindow.showAtLocation(data, Gravity.NO_GRAVITY, xPos, yPos);

        sourceAdapter.setOnItemClickListener((position, string) -> {
            tvUserName.setText(string.getName());
            stateList.get(0).setType(position);
            isStatus = position + 1;
            if (stateList.size() == (position+1)) {
                isStatus = 4;
            }
            page = 1;
            get_WMS_OutboundTaskList();
            dismiss();
        });
    }

    private void dismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 检查请求码和结果码是否匹配
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            // 获取返回的数据
            boolean value = data.getBooleanExtra("name", false);
            // 根据返回的数据刷新界面或数据
            if (value) {
                page = 1;
                get_WMS_OutboundTaskList();
            }
        }
    }
}
